import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppService } from '../../../services/app.service';
import { Router } from '@angular/router';
import { first } from 'rxjs';

import { SidebarComponent } from '../../../modules/sidebar/sidebar.component'; @Component({
  selector: 'app-add-admin',
  standalone: true,
  imports: [SidebarComponent, RouterModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
    HttpClientModule,],
  templateUrl: './add-admin.component.html',
  styleUrl: './add-admin.component.scss'
})
export class AddAdminComponent implements OnInit {
  public addAdminForm: FormGroup;
  public userList: any = [];
  public userListSubscribe: any;
  constructor(private fb: FormBuilder, private appService: AppService, private route: Router) {
    this.addAdminForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      phone: ['', Validators.required],
      privileges: [null, Validators.required],
    });
  }
  async ngOnInit() {
    this.userListSubscribe = await this.appService.loadUser().subscribe(res => {
      console.log('res', res);
     this.userList = res;
    });
  }
  async addAdmin(addAdminForm: any) {
    if (addAdminForm.valid) {
      this.appService.addAdmin(
        addAdminForm.value.username,
        addAdminForm.value.password,
        addAdminForm.value.phone,
        addAdminForm.value.privileges,
      ).pipe(first())
        .subscribe(data => {
          console.log(data);
          if (data.message == 'ADD Admin Success') {
            alert('เพิ่ม Plugins สำเร็จ');
            this.route.navigate(['/admin-page']);
          }
          if (data.message == 'ADD Admin Falied') {
            alert('เพิ่ม Admin ไม่สำเร็จ');
          }
        }, error => {
          alert("เพิ่ม Admin ไม่สำเร็จ");
        })
    }
    if (!addAdminForm.valid) {
      alert("กรุณากรอกให้ครบ");
    }
  }

}

